﻿using UnityEditor;
using UnityEngine;
using YooAsset;

namespace DL.CfgData
{


    public static class ConfigDataHelper
    {
        //指定配置文件名字，读取文件文本
        public static string ReadFileContent(string fileName)
        {
#if UNITY_EDITOR
            if (!Application.isPlaying)
                return ReadConfigFileContent(fileName);
#endif
            var asset = ConfigLoader(fileName);
            return asset != null ? asset.text : null;
        }



        /// <summary>
        /// 编辑器非运行模式下, 读取配置文件
        /// </summary>
#if UNITY_EDITOR
        public static string ReadConfigFileContent(string fileName)
        {
            var searchDir = new string[]
            {
                "Assets/RawResources/ConfigFile",
                "Assets/RawResources/ConfigFile/ClientOnly",
            };
            var append = new string[]
            {
                ".json",
                ".txt",
            };
            foreach (var dir in searchDir)
            {
                foreach (var ext in append)
                {
                    var path = $"{dir}/{fileName}{ext}";
                    var text = AssetDatabase.LoadAssetAtPath<TextAsset>(path);
                    if (text != null)
                        return text.text;
                }
            }

            return string.Empty;
        }
#endif

        public static TextAsset ConfigLoader(string path)
        {
            return !string.IsNullOrEmpty(path) ? LoadAsset<TextAsset>("ConfigFile_" + path) : null;
        }

        public static T LoadAsset<T>(string key) where T : Object
        {
            //TODO 待接入YooAsset
            return YooAssets.LoadAssetSync<T>(key).AssetObject as T;
            // return null;
            // return ResManagerGeneric.Inst.Load<T>(key);
        }
    }
}